package cn.gzsf.weibo.controller;


import cn.gzsf.weibo.mapper.UserMapper;

import cn.gzsf.weibo.pojo.dto.UserLoginDTO;
import cn.gzsf.weibo.pojo.dto.UserRegDTO;
import cn.gzsf.weibo.pojo.entity.User;
import cn.gzsf.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        UserVO u = userMapper.selectByUsername(userRegDTO.getUsername());
        if(u!=null){
            return 2;//代表用户名存在了
        }
        User user = new User();
        //将一个类的同名属性复制到另一个类中，将dto的属性复制给user
        BeanUtils.copyProperties(userRegDTO,user);
        userMapper.insert(user);
        return 1;//注册成功
    }
     @RequestMapping("/login")
    public int login(@RequestBody  UserLoginDTO userLogiDTO, HttpSession session){
         UserVO user = userMapper.selectByUsername(userLogiDTO.getUsername());
         if(user==null){
             return 3;//用户名不存在
         }
         if(user.getPassword().equals(userLogiDTO.getPassword())){
             //把当前登录成功的用户对象保存到会话对象里面
             session.setAttribute("user",user);
             return 1;//登录成功
         }
         return 2;//密码错误
     }

     @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        //从当前客户端对应的会话对象中取出登录成功时保存的用户对象
        return (UserVO)session.getAttribute("user");
     }

     @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除会话对象中的user
        session.removeAttribute("user");
     }
}
